<?php
namespace app\http\middleware;
use think\Controller;
use auth\Action;
use base\BaseMethod;
use wechat\Wechat;
use auth\Api;

/**
* token验证中间件
* Class AuthTokenMiddleware
* @package app\http\middleware
*/
class AuthTokenApi extends Controller
{
	public  		 $errorInfo;   				//错误信息
	public  		 $errorData = [];   		//错误数据
	public  		 $code = -1;   				//错误code
	
	//自执行中间件方法
   	public function handle($request, \Closure $next){
   		
//		$data = [
//			'appkey' => 'B0QEUmyvrPsN5glD',
//			'time'=> Dates::getMillisecond(),
//			'nonce'=> 22
//		];
//		$api = Api::instance();
//		$str = $api->getToken($data);
//		dump($data);
//		dump($str);

		//检测所有请求参数是否有sql注入的风险
		if( $this->is_exist_sql_inject() ){
			return BaseMethod::ReError("监听到存在SQL注入的风险</br>请调整后重新操作！",1006);
		}
		
		$desc = get_method_desc();
		$method = strtolower($desc['method']);
		if( $method !='all' && strtolower($request->method()) != $method){
			return BaseMethod::ReError("不允许".strtolower($request->method()).'请求！');
		}
		//令牌是否存在
		$token = $request->get('token');
		if( $desc['is_need_login'] !='false' && !trim($token) ){
			return BaseMethod::ReError("token 无效！",1004);
		}
		
		//验证令牌
		$api = Api::instance();
		$result = $api->checkToken($token);
		if ($desc['is_need_login'] !='false' && !$result){
			return BaseMethod::ReError($api->errorInfo,$api->errorCode);
		}
		
		
		$request->userInfo = model("user")->where('id',$request->uid)->find();
		$request->userId = $request->uid;
		
        return $next($request);
    }

	//<!--  = 检测是否存在sql注入 =  -->
	private function is_exist_sql_inject(){
		$pattern='/\binsert\s|\bselect\s|\bupdate\s|\bdelete\s|\bcreate\s|\balter\s|\bdrop\s|(\bexec|\bexecute)[\s\(]|\bsp_|\bxp_|\sinto\s/';
		$param =  strtolower(  json_encode($_REQUEST) );
		return preg_match($pattern,$param) ? true : false;
    }
	
	//<!--  = 检测是否村在特殊符号 =  -->
	private function is_exist_special_symbols(){
		$pregs = '/\*|\#/';
		$param =  strtolower(  json_encode($_REQUEST) );
		return preg_match($pregs,$param) ? true : false;
    }
	
}